package com.broad.data.storage.server.service.config;

import com.broad.data.storage.common.model.JwtUser;
import io.jsonwebtoken.*;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenConfiguration {

    @Value("${hos.rest.tokenHeader:hos-header}")
    private String tokenHeader;
    @Value("${host.rest.secretKey:edFmjd3kd}")
    private String secretKey;
    @Value("${host.rest.expiredAfter:30}")
    private int expiredAfter;

    public String createToken(String userName, String uid, int code) {
        final SecretKey key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
        if (!StringUtils.hasText(userName)) {
            throw new RuntimeException("createToken occurs fail;userName:" + userName);
        }
        final Map<String, Object> claims = new HashMap<>();
        claims.put("id", uid);
        claims.put("name", userName);
        claims.put("code", code);
        final Date now = new Date();
        return Jwts.builder().setClaims(claims)
                .setIssuedAt(now).setExpiration(DateUtils.addMinutes(now, expiredAfter))   // 签发时间 & 过期时间
                .signWith(key, SignatureAlgorithm.HS256).compact();
    }


    public int getExpiredAfter() {
        return expiredAfter;
    }

    /**
     * 解密token
     *
     * @param token
     * @return
     */
    public JwtUser checkToken(String token) throws JwtException {
        final SecretKey key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
        JwtUser jwtUser = JwtUser.ofInvalidate();
        JwtParser jwtParser = Jwts.parser().setSigningKey(key);
        Jws<Claims> claims = jwtParser.parseClaimsJws(token);
        Claims claimsBody = claims.getBody();
        String userName = (String) claimsBody.get("name");
        String uid = (String) claimsBody.get("id");
        jwtUser.setValidate(true);
        jwtUser.setName(userName);
        jwtUser.setId(uid);
        jwtUser.setToken(token);
        return jwtUser;
    }

    public String defaultToken() {
        return createToken("default", "default", 0);
    }


    @ConditionalOnMissingBean(name = "jwtTokenConfiguration")
    public JwtTokenConfiguration jwtTokenConfiguration() {
        return new JwtTokenConfiguration();
    }


}
